package com.self.cloudmall.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.self.cloudmall.pms.entity.BrandEntity;
import com.self.cloudmall.pms.entity.CategoryBrandRelationEntity;
import com.self.cloudmall.pms.entity.CategoryEntity;
import com.self.cloudmall.pms.mapper.CategoryBrandRelationMapper;
import com.self.cloudmall.pms.service.BrandService;
import com.self.cloudmall.pms.service.CategoryBrandRelationService;
import com.self.cloudmall.pms.service.CategoryService;
import com.self.cloudmall.pms.utils.PageUtils;
import com.self.cloudmall.pms.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationMapper, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean saveComplete(CategoryBrandRelationEntity categoryBrandRelation) {
        CategoryEntity categoryEntity = categoryService.getById(categoryBrandRelation.getCatelogId());
        BrandEntity brandEntity = brandService.getById(categoryBrandRelation.getBrandId());
        categoryBrandRelation.setBrandName(brandEntity == null? null:brandEntity.getName());
        categoryBrandRelation.setCatelogName(categoryEntity == null ? null:categoryEntity.getName());
        return this.save(categoryBrandRelation);
    }

    @Override
    public List<BrandEntity> relationBrandlist(Long catId) {
        List<CategoryBrandRelationEntity> list = this.lambdaQuery().eq(CategoryBrandRelationEntity::getCatelogId, catId)
                .list();
        if (CollectionUtils.isEmpty(list)){
            return Lists.newArrayList();
        }
        List<Long> collect = list.stream().map(CategoryBrandRelationEntity::getBrandId).collect(Collectors.toList());
        return brandService.listByIds(collect);
    }

}